﻿using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Artech.Core
{
    /// <summary>
    /// This class is used to get and set configuration source.
    /// </summary>
    public  class ConfigurationSourceManager
    {
        private static ConfigurationSourceManager current;
        private IConfigurationSource configSource;
        private ConfigurationSourceManager()
        {}

        /// <summary>
        /// Gets the current <see cref="ConfigurationSourceManager"/>.
        /// </summary>
        /// <value>
        /// The current <see cref="ConfigurationSourceManager"/>.
        /// </value>
        public static ConfigurationSourceManager Current
        {
            get{return current?? (current = new ConfigurationSourceManager());}
        }

        /// <summary>
        /// Gets the configuration source.
        /// </summary>
        /// <value>
        /// The configuration source.
        /// </value>
        public IConfigurationSource ConfigurationSource
        {
            get { return configSource ?? (configSource = ConfigurationSourceFactory.Create()); }
        }

        /// <summary>
        /// Sets the configuration source.
        /// </summary>
        /// <param name="configurationSource">The configuration source.</param>
        public void SetConfigurationSource(IConfigurationSource configurationSource)
        {
            Guard.ArgumentNotNull(configurationSource, "configurationSource");
            configSource = configurationSource;
        }

        /// <summary>
        /// Gets the configuration section.
        /// </summary>
        /// <typeparam name="T">The type of configuration section.</typeparam>
        /// <param name="sectionName">Name of the configuration section.</param>
        /// <returns>The configuration section of the given type.</returns>
        public T GetConfigurationSection<T>(string sectionName) where T : ConfigurationSection
        {
            Guard.ArgumentNotNullOrEmpty(sectionName, "sectionName");
            ConfigurationSection configSection = ConfigurationSource.GetSection(sectionName);
            if (null == configSection)
            {
                return null;
            }
            return (T)configSection;
        }
    }
}